﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OnlineStore.Models;
using OnlineStore.Services;
using OnlineStore.Web.Areas.Admin.Models;
using OrderState = OnlineStore.Models.OrderState;

namespace OnlineStore.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Authorize(Roles = "Admin")]
    public class OrderController : Controller
    {
        private readonly IOrderService _orderService;
        private readonly IAccountService _accountService;

        public OrderController(IOrderService orderService,
            IAccountService accountService)
        {
            _orderService = orderService;
            _accountService = accountService;
        }

        public IActionResult Index(OrderState? state)
        {
            List<Order> orders;

            if (state.HasValue)
            {
                var orderState = state switch
                {
                    OrderState.Completed => OrderState.Completed,
                    OrderState.WaitToDeal => OrderState.WaitToDeal,
                    _ => OrderState.Shipped
                };
                orders = _orderService.FindOrderWithState(orderState);
            }
            else
            {
                orders = _orderService.FindAllOrders();
            }

            return View(orders);
        }


        public IActionResult Send(Guid uid)
        {
            var adminId = Convert.ToInt32(HttpContext.User.Claims.FirstOrDefault(claim => claim.Type == "Id")?.Value);

            var vm = new OrderSendViewModel
            {
                Order = _orderService.FindOrderByUid(uid),
                ContactInfos = _accountService.GetAdminContactInfo(1)
            };
            return View(vm);
        }

        [HttpPost]
        public IActionResult Send(Guid uid, int contactId)
        {
            _orderService.SendOrder(uid, contactId);
            return RedirectToAction(nameof(Index));
        }

        public IActionResult Details(Guid uid)
        {
            var order = _orderService.FindOrderByUid(uid);
            return View(order);
        }
        
    }
}